package create.prototype;

import java.io.*;

/**
 * @author dali
 * @date 2021-07-08 10:25
 * @Description 深拷贝
 */

public class Deep implements Serializable,Cloneable {
    private static final long serialVersionUID = 1L;
    //基本类型
    private String cloneName = "deep";
    //引用类型
    private String[] cloneArr = {"deep"};

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //全部克隆
        Object deep = super.clone();
        Deep deep1 = (Deep) deep;
        //对象引用类型克隆
        deep1.cloneArr = cloneArr.clone();
        return deep1;
    }

    //方式2
    protected Deep getDeep(){
        //创建流对象
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        Deep deep = null;

        try {
            //写入
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //读出
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            deep = (Deep) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
                ois.close();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return deep;
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        //测试方式1
        Deep deep1 = new Deep();
        Deep deep2 = (Deep) deep1.clone();
        deep1.cloneArr[0] = "peed";
        System.out.println("方式一");
        System.out.println(deep1.cloneArr[0]);
        System.out.println(deep2.cloneArr[0]);

        //测试方式2
        Deep deep3 = new Deep();
        Deep deep4 = deep3.getDeep();
        deep3.cloneArr[0] = "pig";
        System.out.println("方式二");
        System.out.println(deep3.cloneArr[0]);
        System.out.println(deep4.cloneArr[0]);
    }
}
